package com.example.shiro;


//自定义的realm域 登录请求之后直接传入这个位子

import com.example.daoman.Permissions;
import com.example.daoman.User;
import com.example.service.impl.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

//@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;

    //    给这个域命名
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }

    //    授权的方法区域
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        /*授权方法
         * 1.根据安全数据获取用户所有的权限操作
         * */
//        1.获取已经认证的用户信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Permissions> p1 = user.getPermissions();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        HashSet<String> hashSet = new HashSet<>();
//        循环遍历添加权限信息
        for (Permissions p:p1){
            hashSet.add(p.getPer());
        }
        info.setStringPermissions(hashSet);
//返回的数据对象
        System.out.println("授权-----------"+ info);
        return info;
    }

    //    用户认证的方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

//        登录请求之后 就会传递token数据传递到这个位置里面来
//        1.获取login传递过来的数据
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());  //原本是一个char数组
//        2.查询数据库
//        判别是用户登录还是管理员登录

        User byUserName = userService.login(username,password);
        if (byUserName != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(byUserName, password, this.getName());
            System.out.println("认证-----------"+info);
            return info;
        }
        return null;
    }
}
